package com.mes.web.controller.common;

import com.mes.common.config.MesConfig;
import com.mes.common.constant.Constants;
import com.mes.common.core.domain.AjaxResult;
import com.mes.common.utils.StringUtils;
import com.mes.common.utils.file.FileUploadUtils;
import com.mes.common.utils.file.FileUtils;
import com.mes.common.utils.file.MimeTypeUtils;
import com.mes.framework.config.ServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.mes.common.utils.file.FileUploadUtils.getExtension;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@RestController
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf('_') + 1);
            String filePath = MesConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
    /**
     * 通用下载请求
     * @param delete 是否删除
     */
    @GetMapping("common/downloadByPath")
    public void fileDownloadByPath(String filePath, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, fileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
//            // 上传文件路径
//            String filePath = MesConfig.getUploadPath();
//            // 上传并返回新文件名称
//            String fileName = FileUploadUtils.upload(filePath, file);
//            String url = serverConfig.getUrl() + fileName;
//            AjaxResult ajax = AjaxResult.success();
//            ajax.put("fileName", fileName);
//            ajax.put("url", url);
//            return ajax;

            // 上传文件路径
            String filePath = MesConfig.getUploadPath();
            System.out.println("上传文件路径"+filePath);
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String extension = getExtension(file);
            for (String s : MimeTypeUtils.IMAGE_EXTENSION) {
                if (s.equals(extension)){
                    System.out.println("文件名称"+fileName);
                    fileName = fileName.replace("\\", "/");
                    String updatedFilePath = removePathBeforeSecondSlash(fileName);
                    System.out.println("拼接的文件名称"+updatedFilePath);
//                    String updatedFilePath = fileName;
                    // 添加水印

                    addWatermark(filePath+updatedFilePath);

//                    String updateFile =filePath+fileName;
//                    String updatedFilePath = removePathBeforeSecondSlash(updateFile);
//                    // 添加水印
//                    System.out.println("添加水印路径"+updatedFilePath);
//                    addWatermark(updatedFilePath);
                }
            }
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
//            ajax.put("fileName", FileUtils.getName(fileName));
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    private String removePathBeforeSecondSlash(String filePath)
    {
        int count = 0;
        int index = -1;
        for (int i = 0; i < filePath.length(); i++) {
            char c = filePath.charAt(i);
            if (c == '/') {
                count++;
                if (count == 6) {
                    index = i;
                    break;
                }
            }
        }
        if (index != -1) {
            System.out.println("截图的index"+index);
            return filePath.substring(index);
        }
        return filePath;
    }

    private String addWatermark(String filePath) throws IOException
    {
//        ClassPathResource resource = new ClassPathResource(filePath);
//        InputStream is = null;
//        try {
//            is = resource.getInputStream();
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath);
//        BufferedImage image = null;
//        try {
//            image = ImageIO.read(inputStream);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        System.out.println("添加水印路径"+filePath);
        File file = new File(filePath);
        System.out.println("file"+file);
        BufferedImage image = ImageIO.read(file);

        // 创建Graphics对象，并设置水印文字的样式
        Graphics2D g2d = (Graphics2D) image.getGraphics();
        Font font = new Font("微软雅黑", Font.BOLD, 40);
        g2d.setFont(font);
        Color watermarkColor = new Color(255, 240, 1, 128);
        g2d.setColor(watermarkColor);

        Color backGroundColor = new Color(255, 255, 255, 255);
        g2d.setBackground(backGroundColor);
        // 在右下角添加水印
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String watermark = sdf.format(new Date());
        int x = image.getWidth() - g2d.getFontMetrics().stringWidth(watermark) - 10;
        int y = image.getHeight() - 10;
        g2d.drawString(watermark, x, y);

        // 保存添加水印后的图片，覆盖原始图片
        File output = new File(filePath);
        ImageIO.write(image, "jpg", output);
        g2d.dispose();
        return filePath;
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = MesConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
}
